package com.nebula.controller.management;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nebula.controller.BaseController;
import com.nebula.common.PageResult;
import com.nebula.entity.Qa;

import com.nebula.service.IQaService;
import com.nebula.service.ISalaryService;
import com.nebula.service.impl.QaServiceImpl;
import com.nebula.service.impl.SalaryServiceImpl;
import com.nebula.vo.QaVo;
import com.nebula.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;

import com.nebula.common.Const;
import com.nebula.common.Result;

/**
 * @author CcccX
 */
@WebServlet(name = "SecurityQuestionController", urlPatterns = "/manage/security")
public class SecurityQuestionController extends BaseController {
    private static final long serialVersionUID = 1L;

    private final IQaService qaService = new QaServiceImpl();

    private final ObjectMapper objectMapper = new ObjectMapper();

    public String index(HttpServletRequest request, HttpServletResponse response) {
        String navId = request.getParameter("id");
        UserVo user = (UserVo) request.getSession().getAttribute(Const.USER_INFO);
        ISalaryService iSalaryService = new SalaryServiceImpl();

        if (iSalaryService.checkNavRole(user.getRoleId(), navId)) {
            return Const.FORWARD + Const.DEFAULT_URL + "website/security-question.jsp";
        }

        return Const.FORWARD + "role-error.jsp";
    }

    public String findByPage(HttpServletRequest request, HttpServletResponse response) {
        String pageStr = request.getParameter("page");
        String rowStr = request.getParameter("rows");

        if (StringUtils.isBlank(pageStr)) {
            pageStr = Const.PAGE;
        }

        if (StringUtils.isBlank(rowStr)) {
            rowStr = Const.SIZE;
        }

        try {
            PageResult<QaVo> pageResult = qaService.findByPage(Integer.parseInt(pageStr), Integer.parseInt(rowStr));
            Map<String, Object> map = new HashMap<>(2);
            map.put("total", pageResult.getTotalCount());
            map.put("rows", pageResult.getList());
            return Const.JSON + objectMapper.writeValueAsString(map);
        } catch (Exception e) {
            e.printStackTrace();
            request.getSession().setAttribute("msg", Const.PROGRAM_EXCEPTION);
            return Const.REDIRECT + Const.MESSAGE_PAGE;
        }
    }

    public String save(HttpServletRequest request, HttpServletResponse response) {
        try {
            String idStr = request.getParameter("qaId");
            String question = request.getParameter("question");
            if (StringUtils.isBlank(question)) {
                return Const.JSON + objectMapper.writeValueAsString(Result.createByErrorMessage("非法参数"));
            }
            Qa qa = new Qa();
            //id为空 执行新增操作
            if (StringUtils.isBlank(idStr)) {
                qa.setQuestion(question);
                qa.setCreatedTime(new Date());
                qa.setUpdatedTime(new Date());
                int save = qaService.save(qa);
                return save > 0 ?
                        Const.JSON + objectMapper.writeValueAsString(Result.createBySuccessMessage("新增成功")) :
                        Const.JSON + objectMapper.writeValueAsString(Result.createByErrorMessage("新增失败"));
            }

            //id不为空，执行更新操作
            qa.setId(Integer.parseInt(idStr));
            qa.setQuestion(question);

            int update = qaService.update(qa);
            return update > 0 ? Const.JSON + objectMapper.writeValueAsString(Result.createBySuccessMessage("保存成功")) :
                    Const.JSON + objectMapper.writeValueAsString(Result.createByErrorMessage("保存失败"));
        } catch (Exception e) {
            e.printStackTrace();
            request.getSession().setAttribute("msg", Const.PROGRAM_EXCEPTION);
            return Const.REDIRECT + Const.MESSAGE_PAGE;
        }
    }

    public String findById(HttpServletRequest request, HttpServletResponse response) {
        try {
            String idStr = request.getParameter("id");
            if (StringUtils.isBlank(idStr)) {
                return Const.JSON + objectMapper.writeValueAsString(Result.createByErrorMessage("非法参数"));
            }
            Qa qa = qaService.findById(Integer.parseInt(idStr));
            return Const.JSON + objectMapper.writeValueAsString(Result.createBySuccess(qa));
        } catch (Exception e) {
            e.printStackTrace();
            request.getSession().setAttribute("msg", Const.PROGRAM_EXCEPTION);
            return Const.REDIRECT + Const.MESSAGE_PAGE;
        }
    }

    public String delete(HttpServletRequest request, HttpServletResponse response) {
        try {
            String idStr = request.getParameter("id");
            if (StringUtils.isBlank(idStr)) {
                return Const.JSON + objectMapper.writeValueAsString(Result.createByErrorMessage("非法参数"));
            }
            int resultCount = qaService.delete(Integer.parseInt(idStr));

            return resultCount > 0 ?
                    Const.JSON + objectMapper.writeValueAsString(Result.createBySuccessMessage("删除成功")) :
                    Const.JSON + objectMapper.writeValueAsString(Result.createByErrorMessage("删除失败"));
        } catch (Exception e) {
            e.printStackTrace();
            request.getSession().setAttribute("msg", Const.PROGRAM_EXCEPTION);
            return Const.REDIRECT + Const.MESSAGE_PAGE;
        }
    }

    public String findAll(HttpServletRequest request, HttpServletResponse response){
        List<QaVo> qaVos = null;
        try {
            qaVos = qaService.findAll();
            return Const.JSON + objectMapper.writeValueAsString(Result.createBySuccess(qaVos));
        } catch (Exception e) {
            e.printStackTrace();
            request.getSession().setAttribute("msg", Const.PROGRAM_EXCEPTION);
            return Const.REDIRECT + Const.MESSAGE_PAGE;
        }
    }
}
